package com.dingreading.cloud.soms.service.impl;

import com.dingreading.cloud.soms.entity.MstXcxMaterialsFiles;
import com.dingreading.cloud.soms.entity.table.MstXcxMaterialsFilesTableDef;
import com.dingreading.cloud.soms.mapper.MstXcxMaterialsFilesMapper;
import com.dingreading.cloud.soms.service.MstXcxMaterialsFilesService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小程序资料文件表 服务层实现。
 *
 * @author EDY
 * @since 2025-11-03
 */
@Service
public class MstXcxMaterialsFilesServiceImpl extends BaseServiceImpl<MstXcxMaterialsFilesMapper, MstXcxMaterialsFiles, MstXcxMaterialsFilesTableDef> implements MstXcxMaterialsFilesService {

    @Override
    protected MstXcxMaterialsFilesTableDef getTable() {
        return MstXcxMaterialsFilesTableDef.mstXcxMaterialsFiles;
    }

    @Override
    public Map<String, List<String>> listByOptionUidsMap(List<String> questionUids) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.questionUid.in(questionUids))
                .and(table.enabled.eq(1));
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(condition);

        // 2. 执行数据库查询
        List<MstXcxMaterialsFiles> xcxMaterialsFiles = getMapper().selectListByQueryAs(queryWrapper, MstXcxMaterialsFiles.class);

        // 3. 处理空结果集
        if (xcxMaterialsFiles == null || xcxMaterialsFiles.isEmpty()) {
            return new java.util.HashMap<>();
        }

        Map<String, List<String>> resultMap = xcxMaterialsFiles.stream()
                .filter(file -> file.getQuestionUid() != null && file.getUrl() != null)
                .collect(Collectors.groupingBy(
                        MstXcxMaterialsFiles::getQuestionUid,
                        Collectors.mapping(MstXcxMaterialsFiles::getUrl, Collectors.toList())
                ));
        return resultMap;
    }
}
